package com.bsoft.advance.client.proxy;

import com.bsoft.advance.core.common.RpcClientProperties;
import com.bsoft.advance.core.register.DiscoveryService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 通过JDK，为接口生成代理类
 */
public class JDKRpcProxy implements RpcProxy{
    @Override
    public <T> T proxyInterface(RpcClientProperties properties, DiscoveryService discoveryService, Class<T> serviceInterface) {
        JDKProxyHandler proxyHandler = new JDKProxyHandler(serviceInterface, properties, discoveryService);
        return (T)Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class[]{serviceInterface}, proxyHandler);
    }

    public class JDKProxyHandler implements InvocationHandler{

        private Class<?> clazz;
        private RpcClientProperties properties;
        private DiscoveryService discoveryService;

        public JDKProxyHandler(Class<?> clazz, RpcClientProperties properties, DiscoveryService discoveryService) {
            this.clazz = clazz;
            this.properties = properties;
            this.discoveryService = discoveryService;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return RpcRequestHandler.invokeRequest(properties, discoveryService, clazz, method, args);
        }


    }
}
